package com.zt.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zt.common.Result;
import com.zt.entity.*;
import com.zt.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 首页统计控制器
 * @author 周明震
 * @date 2025/7/21
 */
@RestController
@RequestMapping("/dashboard")
public class DashboardController {

    @Autowired
    private CoursesService coursesService;

    @Autowired
    private TeachersService teachersService;

    @Autowired
    private SubjectsService subjectsService;

    @Autowired
    private OrdersService ordersService;

    @Autowired
    private UsersService usersService;

    /**
     * 获取首页统计数据
     */
    @GetMapping("/stats")
    public Result<Map<String, Object>> getStats() {
        try {
            Map<String, Object> stats = new HashMap<>();
            
            // 总课程数
            long courseCount = coursesService.count();
            stats.put("courseCount", courseCount);
            
            // 总教师数
            long teacherCount = teachersService.count();
            stats.put("teacherCount", teacherCount);
            
            // 总学员数  todo
            QueryWrapper<Users> userWrapper = new QueryWrapper<>();
            userWrapper.eq("role",1);
            long studentCount = usersService.count(userWrapper);

            stats.put("studentCount", studentCount); // 模拟学员数


            // 计算总营收（已付款订单的总金额）
            QueryWrapper<Orders> paidWrapper = new QueryWrapper<>();
            paidWrapper.eq("status", 3);
            List<Orders> paidOrders = ordersService.list(paidWrapper);
            double totalRevenue = paidOrders.stream()
                    .mapToDouble(order -> order.getAmount() != null ? order.getAmount().doubleValue() : 0.0)
                    .sum();
            stats.put("totalRevenue", totalRevenue);
            
            return Result.success("获取统计数据成功", stats);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取统计数据失败：" + e.getMessage());
        }
    }

    /**
     * 获取课程分类统计
     */
    @GetMapping("/course-category-stats")
    public Result<List<Map<String, Object>>> getCourseCategoryStats() {
        try {
            List<Map<String, Object>> categoryStats = new ArrayList<>();
            
            // 按科目统计课程数量
            List<Subjects> subjects = subjectsService.list();
            for (Subjects subject : subjects) {
                QueryWrapper<Courses> wrapper = new QueryWrapper<>();
                wrapper.eq("subject_id", subject.getId());
                long count = coursesService.count(wrapper);
                
                Map<String, Object> stat = new HashMap<>();
                stat.put("name", subject.getName());
                stat.put("value", count);
                categoryStats.add(stat);
            }
            
            return Result.success("获取课程分类统计成功", categoryStats);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取课程分类统计失败：" + e.getMessage());
        }
    }

    /**
     * 获取最近7天营收数据
     */
    @GetMapping("/daily-revenue")
    public Result<Map<String, Object>> getDailyRevenue() {
        try {
            Map<String, Object> dailyRevenue = new HashMap<>();

            // 生成最近7天的日期
            List<String> dates = new ArrayList<>();
            List<Double> amounts = new ArrayList<>();

            LocalDateTime now = LocalDateTime.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-dd");

            for (int i = 6; i >= 0; i--) {
                LocalDateTime date = now.minusDays(i);
                dates.add(date.format(formatter));

                // 查询当天的营收（已付款订单）
                LocalDateTime startOfDay = date.withHour(0).withMinute(0).withSecond(0);
                LocalDateTime endOfDay = date.withHour(23).withMinute(59).withSecond(59);

                QueryWrapper<Orders> dayWrapper = new QueryWrapper<>();
                dayWrapper.eq("status", 3) // 已付款
                         .between("created_at", startOfDay, endOfDay);

                List<Orders> dayOrders = ordersService.list(dayWrapper);
                double dayRevenue = dayOrders.stream()
                        .mapToDouble(order -> order.getAmount() != null ? order.getAmount().doubleValue() : 0.0)
                        .sum();

                amounts.add(dayRevenue);
            }

            dailyRevenue.put("dates", dates);
            dailyRevenue.put("amounts", amounts);

            return Result.success("获取日营收数据成功", dailyRevenue);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取日营收数据失败：" + e.getMessage());
        }
    }

    /**
     * 获取月营收统计
     */
    @GetMapping("/monthly-revenue")
    public Result<Map<String, Object>> getMonthlyRevenue() {
        try {
            Map<String, Object> monthlyRevenue = new HashMap<>();

            // 生成最近6个月的数据
            List<String> months = new ArrayList<>();
            List<Double> amounts = new ArrayList<>();

            LocalDateTime now = LocalDateTime.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");

            for (int i = 5; i >= 0; i--) {
                LocalDateTime monthDate = now.minusMonths(i);
                months.add(monthDate.format(formatter));

                // 查询当月的营收（已付款订单）
                LocalDateTime startOfMonth = monthDate.withDayOfMonth(1).withHour(0).withMinute(0).withSecond(0);
                LocalDateTime endOfMonth = monthDate.withDayOfMonth(monthDate.toLocalDate().lengthOfMonth())
                        .withHour(23).withMinute(59).withSecond(59);

                QueryWrapper<Orders> monthWrapper = new QueryWrapper<>();
                monthWrapper.eq("status", 3) // 已付款
                           .between("created_at", startOfMonth, endOfMonth);

                List<Orders> monthOrders = ordersService.list(monthWrapper);
                double monthRevenue = monthOrders.stream()
                        .mapToDouble(order -> order.getAmount() != null ? order.getAmount().doubleValue() : 0.0)
                        .sum();

                amounts.add(monthRevenue);
            }

            monthlyRevenue.put("months", months);
            monthlyRevenue.put("amounts", amounts);

            return Result.success("获取月营收数据成功", monthlyRevenue);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取月营收数据失败：" + e.getMessage());
        }
    }
}
